package chaw.android.train;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import chaw.android.util.BoardItem;
import chaw.android.util.HttpRequestManager;
import chaw.android.util.LoadBitMap;
import chaw.android.util.Preferences;
import chaw.android.util.ServerURL;
import chaw.android.util.TimeCheck;

import android.app.ActivityGroup;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ProfileBoardActivity extends ListActivity{
	private ArrayList<BoardItem> list;
	private ArrayList<JSONObject> jlist;
	private BoardAdapter nadapter;
	private ImageButton favorite, talk, station;
	private String userId, check;
	private TextView stations;
	private JSONArray json_arr;
	private ImageView back;
	private String page = "0";
	private View footer = null;
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
        setContentView(R.layout.profile_board);
        favorite = (ImageButton)findViewById(R.id.btnFavorite);
        talk = (ImageButton)findViewById(R.id.btnTalk);
        station = (ImageButton)findViewById(R.id.btnStation);
	    list = new ArrayList<BoardItem>();
	    jlist = new ArrayList<JSONObject>();
        Intent intent = getIntent();
        userId = intent.getExtras().get("user_id").toString();
	    check = intent.getExtras().get("check").toString();
        stations = (TextView)findViewById(R.id.stationName);
        back = (ImageView)findViewById(R.id.btnBack);
		setClickListener();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		setListView();
		if(nadapter!=null)
			nadapter.clear();
		list.clear();
//		getListView().removeAllViews();
	}
	
	private void setListView(){
		Intent intent = getIntent();
		userId = intent.getExtras().get("user_id").toString();
		DownloadAsynkTask task = new DownloadAsynkTask();
		String[] params = new String[]{ ServerURL.userName, "user_id", userId};
		task.execute(params);
	}

	private class DownloadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
	        JSONArray arraydata;
			try {
				arraydata= new JSONArray(result);
				JSONObject jsondata = (JSONObject) arraydata.get(0);
				stations.setText((String)jsondata.get("nick_name"));

				DownloadListAsynkTask task2 = new DownloadListAsynkTask();
				String[] params = new String[]{ ServerURL.downLoadStoriesWithUser , "user_id", userId, "page", page};
				task2.execute(params);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(page.equals("0")){

				Collections.sort(list, boardItemComparator);
				Collections.reverse(list);
				Collections.sort(jlist, boardJsonComparator);
				Collections.reverse(jlist);
				nadapter = new BoardAdapter(getBaseContext(), R.layout.favorite_page_row, R.id.board_title, list);
			    ListView lv = getListView();
			    footer = getLayoutInflater().inflate(R.layout.board_list_footer, null, false);
			    ((ImageButton)footer.findViewById(R.id.add_list)).setImageResource(R.drawable.btn_2);
			    ((ImageButton)footer.findViewById(R.id.add_list)).setOnClickListener(new View.OnClickListener() {			
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						int pages = new Integer(page);
						pages = pages + 10;
						page = ""+pages;
						DownloadAsynkTask task = new DownloadAsynkTask();
						String[] params = new String[]{ ServerURL.downLoadStoriesWithUser, "user_id", userId, "page", page};
						task.execute(params);
		            }
				});

			    lv.addFooterView(footer);
			    lv.setAdapter(nadapter);
			    footer.setVisibility(View.GONE);
			}

		}
	}

	private class DownloadListAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			DownloadAsynkTask2 task = new DownloadAsynkTask2();
			task.execute(new String[]{result});

		}
	}
	private class DownloadAsynkTask2 extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			String response = null;
			try{			
				JSONObject nobject = new JSONObject(urls[0]);
				json_arr = new JSONArray(nobject.getString("boards"));
				for(int i = 0 ; i < json_arr.length(); i++){
					JSONObject json_obj = (JSONObject) json_arr.get(i);
					JSONObject get = (JSONObject) json_obj.get("theme");
					Bitmap image_url = null;
					if(json_obj.get("image_main").toString().equals("0")){
						image_url = null;
					}
					else if(json_obj.get("image_main").toString().equals("1")){
						image_url = LoadBitMap.fromURL(json_obj.get("image_url_1").toString());
					}
					else if(json_obj.get("image_main").toString().equals("2")){
						image_url = LoadBitMap.fromURL(json_obj.get("image_url_2").toString());
					}
					else if(json_obj.get("image_main").toString().equals("3")){
						image_url = LoadBitMap.fromURL(json_obj.get("image_url_3").toString());
					}
					else if(json_obj.get("image_main").toString().equals("4")){
						image_url = LoadBitMap.fromURL(json_obj.get("image_url_4").toString());
					}
					else{
						image_url = null;
					}


					BoardItem input = new BoardItem((String)json_obj.get("board_id"), (String)json_obj.get("title"), (String)get.get("meet"), (String)get.get("restaurant"), (String)get.get("place"), (String)get.get("lodge"), (String)get.get("etc"),image_url,(String)json_obj.get("date"),"", (String)json_obj.get("reply_count"));
					list.add(input);
					list.get(list.size()-1).setStationName(json_obj.getString("station_name"));
					jlist.add(json_obj);
				}
				Log.v("d", nobject.toString());
				response = nobject.get("next_count").toString();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			int next = new Integer(result);
			ListView lv = getListView();
			if(next == 0 || result == null){
				lv.removeFooterView(footer);
			}
			if(nadapter != null){
				nadapter.notifyDataSetChanged();
			    footer.setVisibility(View.VISIBLE);
			}
		}
	}

	private final static Comparator<BoardItem> boardItemComparator= new Comparator<BoardItem>() {
		private final Collator collator = Collator.getInstance();
		@Override
		public int compare(BoardItem object1,BoardItem object2) {
			return collator.compare(object1.getDate(), object2.getDate());
		}
	};

	private final static Comparator<JSONObject> boardJsonComparator= new Comparator<JSONObject>() {
		private final Collator collator = Collator.getInstance();
		@Override
		public int compare(JSONObject object1, JSONObject object2) {
			// TODO Auto-generated method stub
			String date1 = "";
			String date2 = "";
			try {
				date1 = object1.get("date").toString();
				date2 = object2.get("date").toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return collator.compare(date1, date2);
		}
	};



	private class favoriteAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if(result.equals("favorite")){
				Toast.makeText(getBaseContext(), "친구로 등록하였습니다.", Toast.LENGTH_SHORT).show();
				check = result;
			}
			else if(result.equals("deny")){
				Toast.makeText(getBaseContext(), "차단되었습니다.", Toast.LENGTH_SHORT).show();
				check = result;
			}
		}
	}

	private class MakeTalkAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			try {
		        JSONObject resultData = new JSONObject(result);
		        String roomId = resultData.getString("room_id");
		        Intent chatIntent = new Intent(getBaseContext(), ChatRoomActivity.class);
				chatIntent.putExtra("roomId", roomId);
				chatIntent.putExtra("isChat", true);
				startActivity(chatIntent);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void setClickListener(){
		back.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		talk.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				List<String> chatRoomUsers = new ArrayList<String>();
				chatRoomUsers.add(userId);
				chatRoomUsers.add(Preferences.getValue(getBaseContext(), "user_id"));
				
				MakeTalkAsynkTask task = new MakeTalkAsynkTask();
				String[] params = new String[]{ ServerURL.createRoom, 
									"json_string", chatRoomUsers.toString(),
									"user_id_check", Preferences.getValue(getBaseContext(), "user_id"),
									"uuid_check", Preferences.getValue(getBaseContext(), "uuid")};
				task.execute(params);
			}
		});
		favorite.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String url = "";
				if(check.equals("none")){
					url = ServerURL.moveToFavorite;
				}
				else if(check.equals("favorite")){
					url = ServerURL.moveFavoriteToDeny;
				}
				else if(check.equals("deny")){
					url = ServerURL.moveDenyToFavorite;
				}
				favoriteAsynkTask task = new favoriteAsynkTask();
				String[] params = new String[]{ url, "user_id", userId,
									"deny_id", Preferences.getValue(getBaseContext(), "deny_id"),
									"favorite_id", Preferences.getValue(getBaseContext(), "favorite_id"),
									"user_id_check", Preferences.getValue(getBaseContext(), "user_id"),
									"uuid_check", Preferences.getValue(getBaseContext(), "uuid")};
				task.execute(params);
			}
		});
		station.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ActivityGroup parentActivity = (ActivityGroup) getParent();
				Intent intent = new Intent(getBaseContext(), ProfileStationListActivity.class);
				intent.putExtra("user_id", userId);
				intent.putExtra("check", check);
				((FavoriteActivity) parentActivity).startChildActivityWithoutCurrentActivity("ProfileStation", intent);
			}
		});
	}

	private class BoardAdapter extends ArrayAdapter<BoardItem>{
		private ArrayList<BoardItem> items;
		private int rsrc;
		
		public BoardAdapter(Context ctx, int rsrcId, int txtId, ArrayList<BoardItem> data){
			super(ctx, rsrcId, txtId, data);
			this.items = data;
			this.rsrc = rsrcId;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent){
			View v = convertView;
			if(v == null){
				LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(rsrc, null);
			}
			BoardItem e = items.get(position);
			if(e != null){
				String title = e.getTitle();
				if(title.length() > 14){
					title = title.substring(0, 13) + "..";
				}
				((TextView)v.findViewById(R.id.board_title)).setText(title);
				((TextView)v.findViewById(R.id.time)).setText(TimeCheck.checkTime(e.getDate()));
				if(!e.getReplyCount().equalsIgnoreCase("0")){
					((TextView)v.findViewById(R.id.reply_count)).setText(e.getReplyCount());
					((TextView)v.findViewById(R.id.reply_count)).setBackgroundResource(R.drawable.bg_count);
				}
				((TextView)v.findViewById(R.id.stationName)).setText(e.getStationName());

				ImageView image = ((ImageView)v.findViewById(R.id.user_pic));
				if(e.getImage() == null){
					image.setImageResource(R.drawable.icon_nophoto_b);
				}
				else{
					image.setImageBitmap(e.getImage());
				}

				ImageView i = (ImageView)v.findViewById(R.id.theme1);
				if(e.getMeet().equals("1")){
					i.setImageResource(R.drawable.icon_theme_meet);
					i = nextIcon(v,i);
				}
				if(e.getRestaurant().equals("1")){
					i.setImageResource(R.drawable.icon_theme_food);
					i = nextIcon(v,i);
				}
				if(e.getPlace().equals("1")){
					i.setImageResource(R.drawable.icon_theme_tour);
					i = nextIcon(v,i);
				}
				if(e.getLodge().equals("1")){
					i.setImageResource(R.drawable.icon_theme_lodge);
					i = nextIcon(v,i);
				}
				if(e.getEtc().equals("1")){
					i.setImageResource(R.drawable.icon_theme_etc);
					i = nextIcon(v,i);
				}
				v = iconReset(v, i);
			}
			return v;
		}
		public ImageView nextIcon(View v, ImageView i){
			if(i.equals(v.findViewById(R.id.theme1))){
				i = (ImageView)v.findViewById(R.id.theme2);
			}
			else if(i.equals(v.findViewById(R.id.theme2))){
				i = (ImageView)v.findViewById(R.id.theme3);
			}
			else if(i.equals(v.findViewById(R.id.theme3))){
				i = (ImageView)v.findViewById(R.id.theme4);
			}
			else if(i.equals(v.findViewById(R.id.theme4))){
				i = (ImageView)v.findViewById(R.id.theme5);
			}
			return i;
		}
		public View iconReset(View v, ImageView i){
			if(i.equals(v.findViewById(R.id.theme1))){
				((ImageView)v.findViewById(R.id.theme1)).setImageDrawable(null);
				i = (ImageView)v.findViewById(R.id.theme2);
			}
			if(i.equals(v.findViewById(R.id.theme2))){
				((ImageView)v.findViewById(R.id.theme2)).setImageDrawable(null);
				i = (ImageView)v.findViewById(R.id.theme3);
			}
			if(i.equals(v.findViewById(R.id.theme3))){
				((ImageView)v.findViewById(R.id.theme3)).setImageDrawable(null);
				i = (ImageView)v.findViewById(R.id.theme4);
			}
			if(i.equals(v.findViewById(R.id.theme4))){
				((ImageView)v.findViewById(R.id.theme4)).setImageDrawable(null);
				i = (ImageView)v.findViewById(R.id.theme5);
			}
			if(i.equals(v.findViewById(R.id.theme5))){
				((ImageView)v.findViewById(R.id.theme5)).setImageDrawable(null);
			}
			return v;
		}
	}
	@Override
	public void onListItemClick(ListView parent, View v, int position, long id){
		BoardItem output = list.get(position);
		String out = output.getId();

		Intent intent = new Intent(getBaseContext(), ProfileBoardViewActivity.class);
		intent.putExtra("board_id", out);
		intent.putExtra("user_id", userId);
		startActivity(intent);
	}
}
